package com.anxinr.util;

import com.anxinr.constant.RedisConstant;
import com.anxinr.enums.ExceptionEnum;
import com.anxinr.exception.LogicException;
import com.anxinr.pojo.dto.UserDTO;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 当线程进入之后，自动存储当前登录用户信息
 *
 * @author anxinr
 */
@Component
public class UserInfoContext {
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private HttpServletRequest request ;
    /**当前线程信息*/
    private static final ThreadLocal<UserDTO> user = new ThreadLocal<>() ;
    private UserInfoContext(){}

    /**
     * 获取登录用户id
     * @return Long
     */
    public Long getUserId() {
        UserDTO baseUserDTO = getUser();
        if (Objects.isNull(baseUserDTO)){
            /**查看是否登录*/
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                throw new LogicException(ExceptionEnum.STUDY_USER_NAME_ERROR);
            }
            /**解析token*/
            baseUserDTO = redisUtil.getUserInfo(RedisConstant.USER_TOKEN_INFO + token);
            if (Objects.isNull(baseUserDTO)){
                throw new LogicException(ExceptionEnum.STUDY_INVALID_LOGIN_ERROR);
            }
        }
        return baseUserDTO.getId();
    }

    /**
     * 获取用户信息
     * @return UserDTO
     */
    public UserDTO getUser() {
        UserDTO baseUser = user.get();
        if (Objects.isNull(baseUser)){
            /**查看是否登录*/
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                throw new LogicException(ExceptionEnum.STUDY_USER_NAME_ERROR);
            }
            /**解析token*/
            baseUser = redisUtil.getUserInfo(RedisConstant.USER_TOKEN_INFO + token);
            if (Objects.isNull(baseUser)){
                throw new LogicException(ExceptionEnum.STUDY_INVALID_LOGIN_ERROR);
            }
        }
        return baseUser;
    }

    /**
     * 设置用户信息
     * @param baseUser
     */
    public void setUserInfo(UserDTO baseUser) {
        user.set(baseUser);
    }

    /**
     * 删除用户信息
     */
    public void remove() {
        user.remove();
    }
}
